;;
;; bitchin html - html templating for bitchin.
;;

(ns org.mired.bitchin.html
  (:use [clojure.contrib.str-utils :only (str-join re-split)]))

(defmacro make-tags
  ([sep name & names]
     `(do
	(make-tags ~sep ~name)
	(make-tags ~sep ~@names)))
  ([sep name]
     (let [name# (first (re-split #"_" (str name)))]
       `(defn ~name
	  ([] (format "<%s />"  ~name#))
	  ([attribs# & args#]
	     (if (associative? attribs#)
	       (str "<" ~name# (make-attrib-strings attribs#)
		    (if (nil? args#)
		      " />"
		      (format ">%s%s%s</%s>"
			      ~sep (str-join ~sep args#) ~sep ~name#)))
	       (apply ~name (concat [{} attribs#] args#))))))))

(defn quoted-attribute [input]
  (format "\"%s\"" 
	  (apply str (replace {\& "&amp;", \" "&quot;", \> "&gt;"} (str input)))))

(defn- make-attrib-strings [attrs]
  (apply str (map #(format " %s=%s" (if (keyword? %) (name %) %)
			   (quoted-attribute (attrs %)))
		  (keys attrs))))
			   

;; The standard html tags with newlines between element in the contents
(make-tags "\n" html head meta_ base link script style body div dl ol ul li table 
	   tr colgroup col thead tbody tfoot form select input)

;; And now the same, with nothing between elements in the contents.
(make-tags "" title h1 h2 h3 h4 h5 h6 p pre address blockquote hr dd dt th td
	   caption option label textarea button a b i big small strong em q
	   tt a cite dfn abbr acronym code samp kbd var sub del ins font span img
	   br map_ area object param embed noembed)
